﻿using System;
using System.IO;
using System.Runtime.Serialization.Json;

namespace ArienToolkit.Serializer
{
    public class JSON : ISerializer
    {
        public bool Serialize<T>(object obj, string filePath)
        {
            using (FileStream stream = new FileStream(filePath, FileMode.Create))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                try
                {
                    serializer.WriteObject(stream, obj);
                }
                catch (Exception)
                {
                    return true;
                }
                finally
                {
                    stream.Close();
                }
            }
            return true;
        }

        public T DeSerialize<T>(string filePath)
        {
            T obj;

            using (FileStream stream = new FileStream(filePath, FileMode.Open))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                obj = (T)serializer.ReadObject(stream);
            }

            return obj;
        }
    }
}
